<template>
  <n-drawer
    v-model:show="showDrawer"
    placement="right"
    min-w-500
    display-directive="if"
    resizable
  >
    <n-drawer-content title="添加用户" closable>
      <n-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-placement="left"
        :label-width="100"
      >
        <n-form-item label="名称" path="username">
          <n-input
            placeholder="请输入用户名称"
            v-model:value="formData.username"
          />
        </n-form-item>
        <n-form-item label="账号" path="account">
          <n-input
            placeholder="请输入用户账号"
            v-model:value="formData.account"
          />
        </n-form-item>
        <n-form-item label="密码" path="password">
          <n-input
            type="password"
            placeholder="请输入用户密码"
            show-password-on="mousedown"
            v-model:value="formData.password"
          />
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-switch v-model:value="formData.status">
            <template #checked>启用</template>
            <template #unchecked>禁用</template>
          </n-switch>
        </n-form-item>
      </n-form>

      <template #footer>
        <n-space>
          <n-button type="primary" :loading="loading" @click="handleSubmit">
            提交
          </n-button>
          <n-button @click="handleReset">重置</n-button>
          <n-button @click="showDrawer = false">取消</n-button>
        </n-space>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup>
import { FormInst } from "naive-ui";
import { sysUserApi } from "@/api";
import { Emits, formRules } from "./common";

const emits = defineEmits<Emits>();

const initData = () => ({
  username: "",
  account: "",
  password: "",
  status: true,
});
const formRef = ref<FormInst>();
const showDrawer = ref(false);
const loading = ref(false);
const formData = ref<User>(initData());

const handleSubmit = async () => {
  await formRef.value?.validate();
  loading.value = true;
  try {
    const { status } = await sysUserApi.add(formData.value);
    if (!status) return;
    window.$message.success("添加成功");
    showDrawer.value = false;
    emits("submitSuccess");
    handleReset();
  } finally {
    loading.value = false;
  }
};
const handleReset = () => {
  formRef.value?.restoreValidation();
  formData.value = initData();
};

const showDrawerFun = () => (showDrawer.value = true);
defineExpose({ showDrawer: showDrawerFun });
</script>
